<template>
  <el-dialog
      v-model="visible"
      title="运单明细"
      :width="'70%'"
      @close="handleClose"
      :before-close="handleBeforeClose"
      :modal="true"
      custom-class="dialog-with-scroll"
  >
    <template #header>
      <el-row :gutter="20" type="flex" justify="start">
        <el-col :span="5">
          <el-input
              v-model="filters.productName"
              placeholder="物品名称"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="5">
          <el-input
              v-model="filters.productBatch"
              placeholder="物品批次"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="5">
          <el-input
              v-model="filters.origin"
              placeholder="起源地"
              clearable
              size="small"
          />
        </el-col>
        <el-col :span="4">
          <el-button
              type="primary"
              size="small"
              @click="applyFilters"
              style="margin-top: 4px;"
          >
            查询
          </el-button>
          <el-button
              type="success"
              size="small"
              @click="resetFilters"
              style="margin-top: 4px;"
          >
            重置
          </el-button>
        </el-col>
      </el-row>
    </template>

    <template #default>
      <div v-if="details.length" class="total-quantity">
        <p><strong>总数量:</strong> {{ details.length }} 条</p>
      </div>
      <div v-if="details.length" class="table-wrapper">
        <el-table :data="currentDetails" style="width: 100%">
          <el-table-column prop="transportDetailId" label="运单明细ID" width="180"></el-table-column>
          <el-table-column prop="productName" label="物品名称" width="180"></el-table-column>
          <el-table-column prop="productBatch" label="物品批次" width="180"></el-table-column>
          <el-table-column prop="type" label="物品规格" width="180"></el-table-column>
          <el-table-column prop="origin" label="起源地" width="180"></el-table-column>
          <el-table-column prop="weight" label="重量" :formatter="formatWeight" width="180"></el-table-column>
          <el-table-column prop="transportQuantity" label="调拨数量" width="180">
            <template #default="scope">
              {{ scope.row.transportQuantity }} 件
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template v-slot="{ row }">
              <p>{{ row.state === '未送达' ? '未送达' : '已送达' }}</p>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-alert
            title="未找到相关运单明细"
            type="info"
            description="当前运单暂无明细数据"
            show-icon
        />
      </div>
    </template>
    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
      <el-pagination
          v-if="details.length > 0"
          :page-size="pageSize"
          :total="details.length"
          :current-page="currentPage"
          @current-change="handlePageChange"
          layout="prev, pager, next, jumper"
      />
    </template>
  </el-dialog>
</template>

<script>
import { ref, onMounted } from 'vue';
import { getOperatorTransportDetail } from '@/api/delivery/operatorTransport.js';
import { ElMessage } from 'element-plus';

export default {
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    order: {
      type: String,
      required: true
    }
  },
  setup(props, { emit }) {
    const visible = ref(props.modelValue);
    const details = ref([]);
    const pageSize = 10; // 每页显示的条数
    const currentPage = ref(1); // 当前页码
    const currentDetails = ref([]); // 当前页显示的详情

    const updateCurrentDetails = () => {
      const startIndex = (currentPage.value - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      currentDetails.value = details.value.slice(startIndex, endIndex);
    };
    const handlePageChange = (page) => {
      currentPage.value = page;
      updateCurrentDetails();
    };

    const formatSize = (row) => {
      return `${row.size.toFixed(2)} ${row.volumeUnit}`;
    };

    const formatWeight = (row) => {
      return `${row.weight.toFixed(2)} ${row.weightUnit}`;
    };

    const filteredDetails = ref([]);
    const filters = ref({
      productName: '',
      productBatch: '',
      origin: ''
    });

    const applyFilters = () => {
      filteredDetails.value = details.value.filter(detail => {
        return (
            (!filters.value.productName || detail.productName.includes(filters.value.productName)) &&
            (!filters.value.productBatch || detail.productBatch.includes(filters.value.productBatch)) &&
            (!filters.value.origin || detail.origin.includes(filters.value.origin))
        );
      });
      currentDetails.value = filteredDetails.value.slice(0, pageSize);
    };

    const resetFilters = () => {
      filters.value = {
        productName: '',
        productBatch: '',
        origin: ''
      };
      applyFilters();
    };

    const fetchDetails = async () => {
      try {
        console.log('Fetching details for order:', props.order);
        const response = await getOperatorTransportDetail(props.order.trackingNumber);
        details.value = response.data || [];
        return true; // 返回成功标志
      } catch (error) {
        ElMessage.error('获取运单明细失败');
        console.error(error);
        return false; // 返回失败标志
      }
    };

    const handleBeforeClose = (done) => {
      emit('update:modelValue', false); // 关闭时触发更新父组件的状态
      done();
    };

    const handleClose = () => {
      visible.value = false;
    };

    watch(() => props.modelValue, (newVal) => {
      if (newVal) {
        fetchDetails().then(() => {
          visible.value = newVal; // 数据加载完成后显示对话框
          resetFilters();
        });
      } else {
        visible.value = newVal;
      }
    });

    watch(() => props.modelValue, (newVal) => {
      if (newVal) {
        fetchDetails().then(() => {
          resetFilters(); // 数据加载完成后重置过滤器
          applyFilters(); // 应用过滤条件
          visible.value = newVal; // 显示对话框
        });
      } else {
        visible.value = newVal;
      }
    });

    onMounted(() => {
      if (props.modelValue) {
        fetchDetails();
      }
    });

    return {
      visible,
      details,
      handleClose,
      handleBeforeClose,
      handlePageChange,
      applyFilters,
      filteredDetails,
      filters,
      resetFilters,
      pageSize,
      currentPage,
      currentDetails,
      formatSize,
      formatWeight,
    };
  }
};
</script>

<style scoped>
.table-wrapper {
  margin-top: 10px;
}

.el-row {
  margin-bottom: 10px;
}

.el-button {
  margin-top: 4px; /* 调整按钮的上边距 */
}

/* 为 dialog 添加滚动功能 */
.dialog-with-scroll .el-dialog__body {
  max-height: 400px;  /* 设置最大高度 */
  overflow-y: auto;   /* 允许纵向滚动 */
}
</style>
